﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using System.Linq;
using CSUtils;
using U3dUtils;
using UI00;

public class CAssetsLoad {
    public static CAssetsLoad GetInstance {
        get {
            if (instance == null) {
                instance = new CAssetsLoad();
            }
            return instance;
        }
    }
    static CAssetsLoad instance;
    MonoBehaviour mono;

    public void GetAssets(string sourcePath, Action<List<Dictionary<string, FileData>>> callback) {
        this.mono = UIBase.mono;
        mono.StartCoroutine(IGetAssets2(sourcePath, callback));
    }

    IEnumerator IGetAssets2(string sourcePath, Action<List<Dictionary<string, FileData>>> callback) {
        if (Directory.Exists(sourcePath) == false) {
            SystemTipsUI.TipsView("错误", "预览目录不存在");
            yield break;
        }
        var assetsPathDicList = new List<Dictionary<string, FileData>>();
        var dirArr = new DirectoryInfo(sourcePath).GetDirectories("*", SearchOption.AllDirectories);
        Debug.LogError($"文件夹数量_____{dirArr.Length}");
        for (int i3 = 0; i3 < dirArr.Length; i3++) {
            Debug.Log($"文件夹_____{dirArr[i3]}");
            var assetsPathDic = new Dictionary<string, FileData>();
            var fileInfos = dirArr[i3].GetFiles("*.*");
            for (int i4 = 0; i4 < fileInfos.Length; i4++) {
                //Debug.LogFormat("____{0}____{1}___{2}", fileInfos[i].Name, fileInfos[i].Extension, fileInfos[i].FullName);
                var fileInfo = fileInfos[i4];

                var fileData = new FileData();
                fileData.Init(fileInfo);
                if (fileData.type != 0) {
                    assetsPathDic[fileData.assetsPath] = fileData;
                }
                if (fileData.type == EFileType.img) {
                    if (File.Exists(fileData.picPath) == false) {
                        yield return mono.StartCoroutine(IThumbnail(fileData.assetsPath, fileData.picPath));
                    }
                }
            }
            if (assetsPathDic.Count > 0) {
                // assetsPathDic = assetsPathDic.OrderBy(n => n.Key).ToDictionary(n => n.Key, n => n.Value);
                assetsPathDicList.Add(assetsPathDic);
            }
        }
        if (callback != null) {
            callback(assetsPathDicList);
        }
    }

    int limitI = 2048;

    /// <summary>
    /// 压缩
    /// </summary>
    IEnumerator ICompress(string imagePath, Action<Texture2D> action) {
        int qualityI = 100;
        WWW www = new WWW("file:///" + imagePath);
        yield return www;
        if (www.error != null) {
            if (action != null) {
                action(null);
            }
            Debug.LogErrorFormat("缩略图生成失败__{0}__{1}".SetColor("ff0000"), www.error, imagePath);
        } else {
            Texture2D t2d = www.texture;
            byte[] b = t2d.EncodeToJPG(qualityI);
            //Debug.Log( "图原始读取的字节数 " + (b.Length/1000).ToString());
            while ((b.Length / 1024) >= limitI) {
                qualityI -= 5;
                b = t2d.EncodeToJPG(qualityI);
                //Debug.Log ("当前大小："+b.Length/1000);
            }
            Debug.LogFormat("压缩成功，当前大小__{0}____{1}".SetColor("00ff00"), b.Length / 1000, imagePath);
            File.WriteAllBytes(imagePath, b);
            if (action != null) {
                action(t2d);
            }
        }
    }

    int limitI2 = 80;

    /// <summary>
    /// 缩略图
    /// </summary>
    IEnumerator IThumbnail(string imagePath, string picPath) {
        WWW www = new WWW("file:///" + imagePath);
        yield return www;
        if (www.error != null) {
            //action(null);
            Debug.LogError($"缩略图生成失败__{www.error}__{imagePath}".SetColor("ff0000"));
        } else {
            var t2d = www.texture;
            SThumbnail(imagePath, picPath, t2d);
        }
    }

    public static void SWWW(MonoBehaviour mono, string url, Action<WWW> callback) {
        mono.StartCoroutine(IWWW(url, callback));
    }

    static IEnumerator IWWW(string url, Action<WWW> callback) {
        WWW www = new WWW(url);
        yield return www;
        if (www.error != null) {
            if (callback != null) {
                callback(null);
            }
        } else {
            if (callback != null) {
                callback(www);
            }
        }
    }

    public static int thumbnailLenght = 512;

    public static void SThumbnail(string imagePath, string picPath, Texture2D t2d) {
        int qualityI = 30;
        Texture2D nn;
        if (t2d.width >= t2d.height) {
            nn = ScaleTexture(t2d, thumbnailLenght, t2d.height * thumbnailLenght / t2d.width);
        } else {
            nn = ScaleTexture(t2d, t2d.width * thumbnailLenght / t2d.height, thumbnailLenght);
        }
        byte[] b = nn.EncodeToJPG(qualityI);
        Debug.LogFormat("缩略图_压缩成功，当前大小={0}____path={1}".SetColor("00ff00"), b.Length / 1000, imagePath);
        CFile.WriteAllBytes(picPath, b);
    }

    public static Texture2D ScaleTexture(Texture2D source, int targetWidth, int targetHeight) {
        var result = new Texture2D(targetWidth, targetHeight, source.format, false);

        for (int i = 0; i < result.height; ++i) {
            for (int i4 = 0; i4 < result.width; ++i4) {
                Color newColor = source.GetPixelBilinear(i4 / (float)result.width, i / (float)result.height);
                result.SetPixel(i4, i, newColor);
            }
        }
        result.Apply();
        return result;
    }
}

public class FileData {
    public string extension;
    public string name;
    public string dir;
    public string assetsPath;
    public string picPath;
    public EFileType type;

    public void Init(FileInfo fileInfo) {
        extension = fileInfo.Extension.ToLower();
        name = fileInfo.Name;
        dir = fileInfo.DirectoryName;
        assetsPath = fileInfo.FullName;

        switch (extension) {
            case ".jpg":
            case ".png":
            case ".jpeg":
            case ".webp":
                type = EFileType.img;
                break;
            case ".mp3":
                type = EFileType.audio;
                break;
            case ".mp4":
            case ".avi":
                type = EFileType.video;
                break;
        }
        picPath = $"{dir}/.pic/{name}.pic";
    }
}
public enum EFileType {
    text = 1, //
    img = 10, //
    audio = 20, //
    video = 60, //
}
